package com.cinema.servlet.showtime;

import com.cinema.dao.MovieDAO;
import com.cinema.dao.ShowtimeDAO;
import com.cinema.entity.Movie;
import com.cinema.entity.Showtime;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 场次列表Servlet
 */
public class ShowtimeServlet extends HttpServlet {
    private ShowtimeDAO showtimeDAO = new ShowtimeDAO();
    private MovieDAO movieDAO = new MovieDAO();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        String movieIdStr = request.getParameter("movieId");
        
        if (movieIdStr == null || movieIdStr.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/movies");
            return;
        }
        
        try {
            Integer movieId = Integer.parseInt(movieIdStr);
            
            // 获取电影信息
            Movie movie = movieDAO.findById(movieId);
            if (movie == null) {
                request.setAttribute("error", "电影不存在");
                request.getRequestDispatcher("/error/404.jsp").forward(request, response);
                return;
            }
            
            // 获取场次列表
            List<Showtime> showtimes = showtimeDAO.findByMovieId(movieId);
            
            request.setAttribute("movie", movie);
            request.setAttribute("showtimes", showtimes);
            request.getRequestDispatcher("/showtimes.jsp").forward(request, response);
            
        } catch (NumberFormatException e) {
            response.sendRedirect(request.getContextPath() + "/movies");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "获取场次信息失败");
            request.getRequestDispatcher("/error/500.jsp").forward(request, response);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
}
